#include "ucompress.h"
#include <zlib.h>
#include <QFile>
#include <vector>
#include <iostream>
#include <QIODevice>
#include <QDateTime>
#include <QDir>
UCompress::UCompress(QObject *parent)
	: QObject(parent)
{}

UCompress::~UCompress()
{}

bool UCompress::CompressJsonFile(const QString& filename)
{
	QFile file(filename);
    if (!file.exists())
    {
        std::cerr << "文件不存在" << std::endl;
        return false;
    }
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        std::cerr << "文件读取失败" << std::endl;
        return false;  
    }
    QByteArray fileData = file.readAll();
    file.close();
    uLong sourceLen = fileData.size();
    uLongf destLen = compressBound(sourceLen);
    std::vector<Bytef> destBuffer(destLen);
    uLong compressedSize = compress2(destBuffer.data(), &destLen, (const Bytef*)fileData.data(), sourceLen, Z_DEFAULT_COMPRESSION);

    QString timeString = QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss");
    QString fileName_Compressd = "version_" + timeString + ".zlib";
    QDir folder("./versionManagement");
    if (!folder.exists()) {
        if (!folder.mkpath(".")) {
            qDebug() << "无法创建指定文件夹";
            return false;
        }
    }
    QFile fileCompressd(folder.absoluteFilePath(fileName_Compressd));
        if (!fileCompressd.open(QIODevice::WriteOnly)) {
            std::cerr << "无法创建压缩文件" << std::endl;
            return false;
        }
    fileCompressd.write((const char*)destBuffer.data(), destLen);
    fileCompressd.close();
    return true;
}
